In this notebook, a template is provided for you to implement your functionality in stages, which is required to successfully complete this project. If additional code is required that cannot be included in the notebook, be sure that the Python code is successfully imported and included in your submission if necessary.
Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.
In addition to implementing code, there is a writeup to complete. The writeup should be completed in a separate file, which can be either a markdown file or a pdf document. There is a write up template that can be used to guide the writing process. Completing the code template and writeup template will cover all of the rubric points for this project.
The rubric contains "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. The stand out suggestions are optional. If you decide to pursue the "stand out suggestions", you can include the code in this Ipython notebook and also discuss the results in the writeup file.
Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. In addition, Markdown cells can be edited by typically double-clicking the cell to enter edit mode.
# Load pickled data
import pickle
# TODO: Fill this in based on where you saved the training and testing data
training_file = "traffic-signs-data/train.p"
validation_file = "traffic-signs-data/valid.p"
testing_file = "traffic-signs-data/test.p"
sign_names_file = 'signnames.csv'
with open(training_file, mode='rb') as f:
train = pickle.load(f)
with open(validation_file, mode='rb') as f:
valid = pickle.load(f)
with open(testing_file, mode='rb') as f:
test = pickle.load(f)
with open(sign_names_file) as f:
class_names = list(map( lambda x: x.strip().split(',')[1], f.readlines() ))
class_names=class_names[1:] # strip header
X_train, y_train = train['features'], train['labels']
X_valid, y_valid = valid['features'], valid['labels']
X_test, y_test = test['features'], test['labels']
import tensorflow as tf
print(tf.__version__)
The pickled data is a dictionary with 4 key/value pairs:
'features' is a 4D array containing raw pixel data of the traffic sign images, (num examples, width, height, channels).'labels' is a 1D array containing the label/class id of the traffic sign. The file signnames.csv contains id -> name mappings for each id.'sizes' is a list containing tuples, (width, height) representing the the original width and height the image.'coords' is a list containing tuples, (x1, y1, x2, y2) representing coordinates of a bounding box around the sign in the image. THESE COORDINATES ASSUME THE ORIGINAL IMAGE. THE PICKLED DATA CONTAINS RESIZED VERSIONS (32 by 32) OF THESE IMAGESComplete the basic data summary below. Use python, numpy and/or pandas methods to calculate the data summary rather than hard coding the results. For example, the pandas shape method might be useful for calculating some of the summary results.
### Replace each question mark with the appropriate value.
### Use python, pandas or numpy methods rather than hard coding the results
import numpy as np
# TODO: Number of training examples
n_train = np.shape(train['features'])[0]
# TODO: Number of testing examples.
n_test = np.shape(test['features'])[0]
# TODO: What's the shape of an traffic sign image?
image_shape = (np.shape(train['features'])[1], np.shape(train['features'])[2])
# TODO: How many unique classes/labels there are in the dataset.
n_classes = np.size(np.unique(train['labels']))
print("Number of training examples =", n_train)
print("Number of testing examples =", n_test)
print("Image data shape =", image_shape)
print("Number of classes =", n_classes)
Visualize the German Traffic Signs Dataset using the pickled file(s). This is open ended, suggestions include: plotting traffic sign images, plotting the count of each sign, etc.
The Matplotlib examples and gallery pages are a great resource for doing visualizations in Python.
NOTE: It's recommended you start with something simple first. If you wish to do more, come back to it after you've completed the rest of the sections.
### Data exploration visualization code goes here.
### Feel free to use as many code cells as needed.
import matplotlib.pyplot as plt
# Visualizations will be shown in the notebook.
%matplotlib inline
n_train_by_class=[]
for label,name in enumerate(class_names):
n = sum(np.where(y_train==label,1,0))
n_train_by_class.append(n)
plt.rcdefaults()
fig, ax = plt.subplots(figsize=(5,10))
# Example data
y_pos = np.arange(n_classes)
ax.barh(y_pos, n_train_by_class,
color='yellow', ecolor='black')
ax.set_yticks(y_pos)
ax.set_yticklabels(class_names)
ax.invert_yaxis() # labels read top-to-bottom
ax.set_xlabel('Number of Training Examples')
ax.set_title('Number of Training Examples by Class')
plt.show()
r=len(class_names)
c=15
plt.rcdefaults()
fig,ax = plt.subplots(figsize=(10,30))
examples=[]
for idx in range(r+1):
if idx >= len(class_names):
break
cls_idx = np.argwhere(y_train==idx)
np.random.shuffle(cls_idx)
examples.append(np.hstack(X_train[cls_idx[0:c,0]]))
ax.imshow( np.vstack(examples))
ax.set_yticks(np.arange(n_classes)*image_shape[0]+image_shape[0]/2)
ax.set_yticklabels(class_names)
ax.set_xticks([])
plt.show()
from random import sample
from collections import Counter
count_dict = Counter(train['labels'])
labels_count = sorted(count_dict.items(), key=lambda item:item[0])
bar_values = [item[1] for item in labels_count]
bar_labels = [item[0] for item in labels_count]
N = 5
ind = np.arange(n_classes) # the x locations for the groups
width = 0.12 # the width of the bars
fig, ax = plt.subplots()
rects1 = ax.bar(ind, bar_values, width, color='b')
# add some text for labels, title and axes ticks
ax.set_ylabel('Count')
ax.set_title('Distribution of Training Set Labels')
ax.set_xticks(ind + width)
ax.set_xticklabels(bar_labels)
def autolabel(rects):
"""
Attach a text label above each bar displaying its height
"""
for rect in rects:
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width(), 1.05*height,
'%d' % int(height),
ha='center', va='bottom')
autolabel(rects1)
plt.show()
Design and implement a deep learning model that learns to recognize traffic signs. Train and test your model on the German Traffic Sign Dataset.
There are various aspects to consider when thinking about this problem:
Here is an example of a published baseline model on this problem. It's not required to be familiar with the approach used in the paper but, it's good practice to try to read papers like these.
NOTE: The LeNet-5 implementation shown in the classroom at the end of the CNN lesson is a solid starting point. You'll have to change the number of classes and possibly the preprocessing, but aside from that it's plug and play!
Use the code cell (or multiple code cells, if necessary) to implement the first step of your project.
### Preprocess the data here. Preprocessing steps could include normalization, converting to grayscale, etc.
### Feel free to use as many code cells as needed.
import random
import cv2
# Randomly rotate training set. ([-15, 15] angles)
rotated_train = {'features': [], 'labels': []}
for img, label in zip(train['features'], train['labels']):
RotateMatrix = cv2.getRotationMatrix2D(center=(img.shape[1]/2, img.shape[0]/2), angle=random.uniform(-15, 15), scale=1)
rotated_train['features'].append(cv2.warpAffine(img, RotateMatrix, (img.shape[0], img.shape[1])))
rotated_train['labels'].append(label)
# Randomly perturbe training set in position. (on x/y axis, [-2,2] pixels)
perturbed_train = {'features': [], 'labels': []}
for img, label in zip(train['features'], train['labels']):
pixel = random.sample([-2, -1, 1, 2], 1)[0]
TranslationMatrix = np.array([[1, 0, pixel],
[0, 1, 0]], dtype=np.float32)
perturbed_train['features'].append(cv2.warpAffine(img, TranslationMatrix, (img.shape[0], img.shape[1])))
perturbed_train['labels'].append(label)
pixel = random.sample([-2, -1, 1, 2], 1)[0]
TranslationMatrix = np.array([[1, 0, 0],
[0, 1, pixel]], dtype=np.float32)
perturbed_train['features'].append(cv2.warpAffine(img, TranslationMatrix, (img.shape[0], img.shape[1])))
perturbed_train['labels'].append(label)
big_train = {
'features':
np.concatenate([train['features'], rotated_train['features'], perturbed_train['features']]),
'labels':
np.concatenate([train['labels'], rotated_train['labels'], perturbed_train['labels']])
}
print(np.shape(big_train['features']), np.shape(big_train['labels']))
sample_idxes = sample(range(n_train), 3)
fig = plt.figure()
for i in range(3):
ax = fig.add_subplot(2, 3, i+1)
img = train['features'][sample_idxes[i],:,:,:]
ax.imshow(img)
RotateMatrix = cv2.getRotationMatrix2D(center=(img.shape[1]/2, img.shape[0]/2), angle=random.uniform(-15, 15), scale=1)
rotated_img = cv2.warpAffine(img, RotateMatrix, (img.shape[0], img.shape[1]))
ax = fig.add_subplot(2, 3, i+4)
ax.imshow(rotated_img)
plt.show()
fig = plt.figure()
for i in range(3):
img = train['features'][sample_idxes[i],:,:,:]
pixel = random.sample([-2, -1, 1, 2], 1)[0]
TranslationMatrix = np.array([[1, 0, pixel],
[0, 1, 0]], dtype=np.float32)
vertical_img = cv2.warpAffine(img, TranslationMatrix, (img.shape[0], img.shape[1]))
ax = fig.add_subplot(2, 3, i+1)
ax.imshow(vertical_img)
pixel = random.sample([-2, -1, 1, 2], 1)[0]
TranslationMatrix = np.array([[1, 0, 0],
[0, 1, pixel]], dtype=np.float32)
he_img = cv2.warpAffine(img, TranslationMatrix, (img.shape[0], img.shape[1]))
ax = fig.add_subplot(2, 3, i+4)
ax.imshow(he_img)
plt.show()
gray_train = [cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) for image in big_train['features']]
gray_valid = [cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) for image in valid['features']]
gray_test = [cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) for image in test['features']]
gray_train = np.reshape(gray_train, (len(gray_train), 32, 32, -1))
gray_valid = np.reshape(gray_valid, (len(gray_valid), 32, 32, -1))
gray_test = np.reshape(gray_test, (len(gray_test), 32, 32, -1))
print(np.shape(gray_train))
fig = plt.figure()
for i in range(3):
ax = fig.add_subplot(2, 3, i+1)
img = train['features'][sample_idxes[i],:,:,:]
ax.imshow(img)
img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
ax = fig.add_subplot(2, 3, i+4)
ax.imshow(img, 'gray')
plt.show()
### Define your architecture here.
### Feel free to use as many code cells as needed.
import tensorflow as tf
from sklearn.utils import shuffle
from tensorflow.contrib.layers import flatten
EPOCHS = 60
BATCH_SIZE = 100
rate = 0.001
mu = 0
sigma = 0.1
l2_lambda = 5e-4
def conv2d(x, W, b, strides=1, padding='VALID'):
x = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding=padding)
x = tf.nn.bias_add(x, b)
return tf.nn.relu(x)
def maxpool2d(x, k=2):
return tf.nn.max_pool(
x,
ksize=[1, k, k, 1],
strides=[1, k, k, 1],
padding='VALID')
def lrn(inputs, depth_radius=2, alpha=0.0001, beta=0.75, bias=1.0):
return tf.nn.local_response_normalization(inputs, depth_radius=depth_radius, alpha=alpha, beta=beta, bias=bias)
x = tf.placeholder(tf.float32, (None, 32, 32, 1))
y = tf.placeholder(tf.int32, (None))
keep_prob = tf.placeholder(tf.float32)
one_hot_y = tf.one_hot(y, n_classes)
with tf.name_scope('Variances'):
weights = {
'wc1_1': tf.Variable(tf.truncated_normal([9, 9, 1, 32])),
'wc1_2': tf.Variable(tf.truncated_normal([5, 5, 1, 32])),
'wc2_1': tf.Variable(tf.truncated_normal([5, 5, 32, 128])),
'wc2_2': tf.Variable(tf.truncated_normal([9, 9, 32, 128])),
'wc3': tf.Variable(tf.truncated_normal([3, 3, 256, 512])),
'wd1': tf.Variable(tf.truncated_normal([8192, 2048])),
'wd2': tf.Variable(tf.truncated_normal([2048, 2048])),
'out': tf.Variable(tf.truncated_normal([2048, n_classes]))}
biases = {
'bc1_1': tf.Variable(tf.truncated_normal([32])),
'bc1_2': tf.Variable(tf.truncated_normal([32])),
'bc2_1': tf.Variable(tf.truncated_normal([128])),
'bc2_2': tf.Variable(tf.truncated_normal([128])),
'bc3': tf.Variable(tf.truncated_normal([512])),
'bd1': tf.Variable(tf.truncated_normal([2048])),
'bd2': tf.Variable(tf.truncated_normal([2048])),
'out': tf.Variable(tf.truncated_normal([n_classes]))}
with tf.name_scope('conv1_1'):
conv1_1 = conv2d(x, weights['wc1_1'], biases['bc1_1'])
conv1_1 = lrn(conv1_1)
with tf.name_scope('pool1_1'):
conv1_1 = maxpool2d(conv1_1, k=2)
with tf.name_scope('conv1_2'):
conv1_2 = conv2d(x, weights['wc1_2'], biases['bc1_2'], padding='SAME')
conv1_2 = lrn(conv1_2)
with tf.name_scope('pool1_2'):
conv1_2 = maxpool2d(conv1_2, k=2)
with tf.name_scope('conv2_1'):
conv2_1 = conv2d(conv1_1, weights['wc2_1'], biases['bc2_1'])
conv2_1 = lrn(conv2_1)
# conv2_1 = maxpool2d(conv2_1, k=2)
with tf.name_scope('conv2_2'):
conv2_2 = conv2d(conv1_2, weights['wc2_2'], biases['bc2_2'])
conv2_2 = lrn(conv2_2)
# conv2_2 = maxpool2d(conv2_2, k=2)
with tf.name_scope('conv3'):
reshaped_conv = tf.concat(1, [tf.reshape(conv2_1, [-1, 8192]), tf.reshape(conv2_2, [-1, 8192])])
reshaped_conv = tf.reshape(reshaped_conv, [-1, 8, 8, 256])
conv3 = conv2d(reshaped_conv, weights['wc3'], biases['bc3'], padding='SAME')
with tf.name_scope('pool3'):
conv3 = maxpool2d(conv3, k=2)
reshaped_conv3 = tf.reshape(conv3, [-1, 8192])
with tf.name_scope('fc1'):
fc1 = tf.add(tf.matmul(reshaped_conv3, weights['wd1']), biases['bd1'])
fc1 = tf.nn.relu(fc1)
# fc1 = tf.nn.dropout(fc1, keep_prob)
with tf.name_scope('fc2'):
fc2 = tf.add(tf.matmul(fc1, weights['wd2']), biases['bd2'])
fc2 = tf.nn.relu(fc2)
# fc2 = tf.nn.dropout(fc2, keep_prob)
with tf.name_scope('output'):
logits = tf.add(tf.matmul(fc2, weights['out']), biases['out'])
predicts = tf.argmax(logits, 1)
with tf.name_scope('loss'):
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits, one_hot_y)
loss_operation = tf.reduce_mean(cross_entropy)
for weights, biases in zip(weights.values(), biases.values()):
loss_operation += l2_lambda * (tf.nn.l2_loss(weights) + tf.nn.l2_loss(biases))
summary = [tf.summary.scalar('Log_Loss', tf.log(loss_operation))]
with tf.name_scope('optimizer'):
global_step = tf.Variable(0)
lr = 0.001
dr = 0.96
learning_rate = tf.train.exponential_decay(
learning_rate=lr,
global_step=global_step*BATCH_SIZE,
decay_steps=20,
decay_rate=dr,
staircase=True
)
optimizer = tf.train.AdamOptimizer(learning_rate)
training_operation = optimizer.minimize(loss_operation)
with tf.name_scope('accuracy'):
correct_prediction = tf.equal(predicts, tf.argmax(one_hot_y, 1))
accuracy_operation = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
merged_summary = tf.summary.merge(summary)
writer = tf.summary.FileWriter('./board', tf.get_default_graph())
A validation set can be used to assess how well the model is performing. A low accuracy on the training and validation sets imply underfitting. A high accuracy on the test set but low accuracy on the validation set implies overfitting.
### Train your model here.
### Calculate and report the accuracy on the training and validation set.
### Once a final model architecture is selected,
### the accuracy on the test set should be calculated and reported as well.
### Feel free to use as many code cells as needed.
def evaluate(X_data, y_data, kp=1.):
num_examples = len(X_data)
total_accuracy = 0
sess = tf.get_default_session()
for offset in range(0, num_examples, BATCH_SIZE):
batch_x, batch_y = X_data[offset:offset+BATCH_SIZE], y_data[offset:offset+BATCH_SIZE]
accuracy = sess.run(accuracy_operation, feed_dict={x: batch_x, y: batch_y, keep_prob:kp})
total_accuracy += (accuracy * len(batch_x))
return total_accuracy / num_examples
sess = tf.Session()
with sess.as_default():
sess.run(tf.global_variables_initializer())
num_examples = len(gray_train)
print("Training...")
print()
k = 1
for i in range(EPOCHS):
X_train, y_train = shuffle(gray_train, big_train['labels'])
for offset in range(0, num_examples, BATCH_SIZE):
end = offset + BATCH_SIZE
batch_x, batch_y = X_train[offset:end], y_train[offset:end]
_, summary_result = sess.run([training_operation, merged_summary], feed_dict={x: batch_x, y: batch_y, keep_prob: .5})
writer.add_summary(summary_result, k)
k += 1
# train_accuracy = evaluate(batch_x, batch_y)
# validation_accuracy = evaluate(gray_valid, valid['labels'])
# print("Train Accuracy = {:.9f}".format(train_accuracy))
# print("Validation Accuracy = {:.9f}".format(validation_accuracy))
# print()
train_accuracy = evaluate(gray_train, big_train['labels'])
validation_accuracy = evaluate(gray_valid, valid['labels'])
print("EPOCH {} ...".format(i+1))
print("Train Accuracy = {:.9f}".format(train_accuracy))
print("Validation Accuracy = {:.9f}".format(validation_accuracy))
print()
saver = tf.train.Saver(tf.global_variables())
saver.save(sess,"checkpoint.data")
with sess.as_default():
test_accuracy = evaluate(gray_test, test['labels'])
print("Test Accuracy = {:.9f}".format(test_accuracy))
To give yourself more insight into how your model is working, download at least five pictures of German traffic signs from the web and use your model to predict the traffic sign type.
You may find signnames.csv useful as it contains mappings from the class id (integer) to the actual sign name.
### Load the images and plot them here.
### Feel free to use as many code cells as needed.
import os
test_images = os.listdir('./testimgs')
testdata = [cv2.resize(cv2.imread('./testimgs/' + image),(32,32),interpolation=cv2.INTER_AREA) for image in test_images]
fig = plt.figure()
for i in range(len(testdata)):
ax = fig.add_subplot(2, 3, i+1)
ax.imshow(testdata[i])
plt.show()
For first image, the label is **
### Run the predictions here and use the model to output the prediction for each image.
### Make sure to pre-process the images with the same pre-processing pipeline used earlier.
### Feel free to use as many code cells as needed.
gray_testdata = [cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) for image in testdata]
gray_testdata = np.reshape(gray_testdata, (len(gray_testdata), 32, 32, -1))
with sess.as_default():
softmax_probabilities, results = sess.run([tf.nn.softmax(logits), predicts], feed_dict={x: gray_testdata, keep_prob: 1.})
print(results)
According to the signames.csv file, the prediction result are as follows:
So, the model predicted all of these signs correctly, it's 100% accurate on these new images.
For each of the new images, print out the model's softmax probabilities to show the certainty of the model's predictions (limit the output to the top 5 probabilities for each image). tf.nn.top_k could prove helpful here.
The example below demonstrates how tf.nn.top_k can be used to find the top k predictions for each image.
tf.nn.top_k will return the values and indices (class ids) of the top k predictions. So if k=3, for each sign, it'll return the 3 largest probabilities (out of a possible 43) and the correspoding class ids.
Take this numpy array as an example. The values in the array represent predictions. The array contains softmax probabilities for five candidate images with six possible classes. tk.nn.top_k is used to choose the three classes with the highest probability:
# (5, 6) array
a = np.array([[ 0.24879643, 0.07032244, 0.12641572, 0.34763842, 0.07893497,
0.12789202],
[ 0.28086119, 0.27569815, 0.08594638, 0.0178669 , 0.18063401,
0.15899337],
[ 0.26076848, 0.23664738, 0.08020603, 0.07001922, 0.1134371 ,
0.23892179],
[ 0.11943333, 0.29198961, 0.02605103, 0.26234032, 0.1351348 ,
0.16505091],
[ 0.09561176, 0.34396535, 0.0643941 , 0.16240774, 0.24206137,
0.09155967]])
Running it through sess.run(tf.nn.top_k(tf.constant(a), k=3)) produces:
TopKV2(values=array([[ 0.34763842, 0.24879643, 0.12789202],
[ 0.28086119, 0.27569815, 0.18063401],
[ 0.26076848, 0.23892179, 0.23664738],
[ 0.29198961, 0.26234032, 0.16505091],
[ 0.34396535, 0.24206137, 0.16240774]]), indices=array([[3, 0, 5],
[0, 1, 4],
[0, 5, 1],
[1, 3, 5],
[1, 4, 3]], dtype=int32))
Looking just at the first row we get [ 0.34763842, 0.24879643, 0.12789202], you can confirm these are the 3 largest probabilities in a. You'll also notice [3, 0, 5] are the corresponding indices.
with sess.as_default():
top_5_logits = sess.run(tf.nn.top_k(logits, k=5), feed_dict={x: gray_testdata, keep_prob: 1.})
print(top_5_logits)
### Print out the top five softmax probabilities for the predictions on the German traffic sign images found on the web.
### Feel free to use as many code cells as needed.
with sess.as_default():
top_probablities = sess.run(tf.nn.top_k(softmax_probabilities))
import pandas as pd
def get_label_map(filename, questnums):
label_df = pd.read_csv(filename)
label_map = []
for questnum in questnums:
label_map.extend(label_df[label_df['ClassId']==questnum].SignName.get_values())
return label_map
top_labels = [get_label_map('signnames.csv', index) for index in top_probablities.indices]
top_labels
for i, (labels, probs, candidate) in enumerate(zip(top_probablities.indices,top_probablities.values, testdata)):
fig = plt.figure(figsize=(15,2))
plt.bar(labels, probs)
plt.title(top_labels[i][0])
height = candidate.shape[0]
plt.xticks(np.arange(.5, 43.5, 1.), get_label_map('signnames.csv', np.unique(y_train)), ha='right', rotation=45)
plt.yticks(np.arange(0., 1., .1), np.arange(0., 1., .1))
ax = plt.axes([.75, .25, .5, .5], frameon=True)
ax.imshow(candidate)
ax.axis('off')
plt.show()
Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the IPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.